package com.portal.cwegportal.service;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.jz.page.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.portal.cwegportal.customenum.FileBusinessType;
import com.portal.cwegportal.customenum.FileClass;
import com.portal.cwegportal.input.browserecord.CreateBrowseRecordInput;
import com.portal.cwegportal.input.browserecord.GetBrowseCountInput;
import com.portal.cwegportal.input.publicationannouncement.PageLoadInput;
import com.portal.cwegportal.input.publicationannouncement.*;
import com.portal.cwegportal.mapper.PublicationAnnouncementMapper;
import com.portal.cwegportal.mapper.ColumnPlateMapper;
import com.portal.cwegportal.mapper.ReleaseScopeMapper;
import com.portal.cwegportal.model.*;
import com.portal.cwegportal.model.Tool.PrivilegeTool;
import com.portal.cwegportal.output.publicationannouncement.PageLoadOutput;
import com.portal.cwegportal.output.publicationannouncement.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import static org.apache.http.util.TextUtils.isBlank;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 *  创建人:王增立
 *  备注: 公告、发文的服务
 *  时间: 2019/4/26 15:22
 *  参数: 
 */
@Service
public class PublicationAnnouncementService {

    @Autowired
    PublicationAnnouncementMapper publicationAnnouncementMapper;
    @Autowired
    ColumnPlateMapper columnPlateMapper;
    @Autowired
    ReleaseScopeMapper releaseScopeMapper;
    @Autowired
    FileService fileService;
    @Autowired
    BrowseRecordService browseRecordService;
    @Autowired
    PrivilegeService privilegeService;
/**
 *  创建人:王增立
 *  备注: 创建公告、发文
 *  时间: 2019/4/26 15:23
 *  参数: 
 */
    @Transactional
    public CreatePublicationAnnouncementOutput createPublicationAnnouncement(CreatePublicationAnnouncementInput input) throws Exception {
        CreatePublicationAnnouncementOutput output = new CreatePublicationAnnouncementOutput();
        PublicationAnnouncement PublicationAnnouncement=new PublicationAnnouncement();

        ObjectUnit.Copy(input.getItem(),PublicationAnnouncement);

        PublicationAnnouncement.setDeleted(false);
        PublicationAnnouncement.setGmtCreate(new Date());
        PublicationAnnouncement.setGmtModified(new Date());
       // PublicationAnnouncement.setReleaseTime(new Date());

        PublicationAnnouncement.setCreatorCode(CurrentUser.getUserCode());
        PublicationAnnouncement.setCreatorId(CurrentUser.getUserId());
        PublicationAnnouncement.setCreatorCode(CurrentUser.getUserCode());

        //publicationAnnouncementMapper.insertPublicationAnnouncementAndGetId(PublicationAnnouncement);
        if(PublicationAnnouncement.getId()!=null) {
            publicationAnnouncementMapper.deleteByPrimaryKey(PublicationAnnouncement.getId());
            releaseScopeMapper.deleteByKeyId(PublicationAnnouncement.getId().toString(),PublicationAnnouncement.getPublishType());
            PublicationAnnouncement.setId(null);
        }
        publicationAnnouncementMapper.insertSelective(PublicationAnnouncement);
        input.getReleaseScopes().forEach((k) -> {
            k.setKeyId(PublicationAnnouncement.getId());
            k.setGmtCreate(new Date());
            k.setGmtModified(new Date());
            k.setCreatorCode("");
            k.setCreatorId("");
            k.setCreatorName("");
            k.setPublishType(input.getItem().getPublishType());
          //  k.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
           // k.setPublishingDepartment(input.getItem().getPublishingDepartment());
        });
        releaseScopeMapper.insertEleaseScopes(input.getReleaseScopes());
        fileService.saveFiles(input.getItem().getFiles(), PublicationAnnouncement.getId().toString(), FileBusinessType.PublicationAnnouncement.toString());
        output.setItem(PublicationAnnouncement);
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 删除公告、发文
 *  时间: 2019/4/26 15:23
 *  参数: 
 */
    public DeletePublicationAnnouncementOutput deletePublicationAnnouncement(DeletePublicationAnnouncementInput input) {
        DeletePublicationAnnouncementOutput output = new DeletePublicationAnnouncementOutput();
        PublicationAnnouncement oldEntity = publicationAnnouncementMapper.selectByPrimaryKey(input.getItem().getId());
        oldEntity.setDeleted(true);
        publicationAnnouncementMapper.updateByPrimaryKey(oldEntity);
        output.setItem(oldEntity);
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 修改公告、发文
 *  时间: 2019/4/26 15:23
 *  参数: 
 */
    @Transactional
    public EditPublicationAnnouncementOutput editPublicationAnnouncement (EditPublicationAnnouncementInput input) throws Exception{
        EditPublicationAnnouncementOutput output=new EditPublicationAnnouncementOutput();
        PublicationAnnouncement oldEntity= publicationAnnouncementMapper.selectByPrimaryKey(input.getItem().getId());
        //oldEntity.setLinkName(input.getItem().getLinkName());
        //oldEntity.setLinkDesc(input.getItem().getLinkDesc());
        oldEntity.setTitle(input.getItem().getTitle());
        oldEntity.setContent(input.getItem().getContent());
        oldEntity.setPublishType(input.getItem().getPublishType());
        oldEntity.setPublishTypeName(input.getItem().getPublishTypeName());
        oldEntity.setPublisherName(input.getItem().getPublisherName());
        oldEntity.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
        oldEntity.setPublishingDepartment(input.getItem().getPublishingDepartment());
        oldEntity.setGmtModified(new Date());
        oldEntity.setReleaseTime(input.getItem().getReleaseTime());

        releaseScopeMapper.deleteByKeyId(oldEntity.getId().toString(),oldEntity.getPublishType());

        input.getReleaseScopes().forEach((k) -> {
            k.setKeyId(oldEntity.getId());
            k.setGmtCreate(new Date());
            k.setGmtModified(new Date());
            k.setCreatorCode("");
            k.setCreatorId("");
            k.setCreatorName("");
            k.setPublishType(input.getItem().getPublishType());
            //k.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
            //k.setPublishingDepartment(input.getItem().getPublishingDepartment());
        });
        releaseScopeMapper.insertEleaseScopes(input.getReleaseScopes());
        publicationAnnouncementMapper.updateByPrimaryKey(oldEntity);
        output.setItem(oldEntity);
        return  output;
    }

/**
 *  创建人:王增立
 *  备注: 根据条件查询公告、发文
 *  时间: 2019/4/26 15:24
 *  参数: 
 */
    public GetPublicationAnnouncementOutput getPublicationAnnouncement(GetPublicationAnnouncementInput input) throws Exception  {
        GetPublicationAnnouncementOutput output = new GetPublicationAnnouncementOutput();

        Example example = new Example(PublicationAnnouncement.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("deleted", 0);
        criteria.andLike("title", "%"+input.getTitle()+"%");

        if (!isBlank(input.getStatus())) {
            criteria.andEqualTo("status", input.getStatus());//普通用户只查询已发布的
        }
        if (!isBlank(input.getPublishType()))
        {
            criteria.andEqualTo("publishType", input.getPublishType());
        }

        if (!isBlank(input.getColumnPlateCode()))
        {
            criteria.andEqualTo("columnPlateCode", input.getColumnPlateCode());
        }
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath(input.getPublishType());//1新闻2公告3发文4学院天地
        if(!PrivilegeToolList.isErre()&&!PrivilegeToolList.isAdmin()&&PrivilegeToolList.getPrivilegeLiat().size()>0){
            criteria.andIn("id",PrivilegeToolList.getPrivilegeLiat());
        }else if(PrivilegeToolList.isErre()){
            //错误条件不会查到信息
            criteria.orEqualTo("status",500);
        }
        if (!PrivilegeToolList.isAdmin()) {
            criteria.andEqualTo("status", 1);//普通用户只查询已发布的
        }
        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"Id desc");
        List<PublicationAnnouncement> ls=publicationAnnouncementMapper.selectByExample(example);
        PageInfo<PublicationAnnouncement> page = new PageInfo<>(ls);

        //浏览次数
        List<PublicationAnnouncement> lsResult=page.getList();
        lsResult.forEach(it->{

            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);

        });

        output.setItems(new PagedResult<PublicationAnnouncement>(lsResult,(int)page.getTotal()));
        return  output;

    }
/**
 *  创建人:王增立
 *  备注: 加载过滤
 *  时间: 2019/4/26 15:24
 *  参数: 
 */
    public PageLoadOutput pageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();

        Example example = new Example(PublicationAnnouncement.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("deleted", 0);
        //criteria.andLike("title", "%"+input.getTitle()+"%");

        if (!isBlank(input.getStatus())) {
            criteria.andEqualTo("status", input.getStatus());//普通用户只查询已发布的
        }
        if (!isBlank(input.getPublishType()))
        {
            criteria.andEqualTo("publishType", input.getPublishType());
        }
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath(input.getPublishType());//1新闻2公告3发文4学院天地
        if(!PrivilegeToolList.isErre()&&!PrivilegeToolList.isAdmin()&&PrivilegeToolList.getPrivilegeLiat().size()>0){
            criteria.andIn("id",PrivilegeToolList.getPrivilegeLiat());
        }else if(PrivilegeToolList.isErre()){
            //错误条件不会查到信息
            criteria.orEqualTo("status",500);
        }
        if (!PrivilegeToolList.isAdmin()) {
            criteria.andEqualTo("status", 1);//普通用户只查询已发布的
        }
        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"Id desc");
        List<PublicationAnnouncement> ls=publicationAnnouncementMapper.selectByExample(example);

        Example exampleTwo = new Example(ColumnPlate.class);
        Example.Criteria criteriaTwo = exampleTwo.createCriteria();
        criteriaTwo.andEqualTo("keyType", input.getPublishType());//1新闻2公告3发文4学院天地
        criteriaTwo.andEqualTo("deleted",0);
        List<ColumnPlate> lsTwo = columnPlateMapper.selectByExample(exampleTwo);
        output.setColumnPlates(lsTwo);
        //output.setItems(getPublicationAnnouncement(input).getItems());
        PageInfo<PublicationAnnouncement> page = new PageInfo<>(ls);

        //浏览次数
        List<PublicationAnnouncement> lsResult=page.getList();
        lsResult.forEach(it->{
            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);
        });
        output.setItems(new PagedResult<PublicationAnnouncement>(lsResult,(int)page.getTotal()));
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 根据Id获取公告、发文信息
 *  时间: 2019/4/26 15:24
 *  参数: 
 */
    public GetPublicationAnnouncementOutput getPublicationAnnouncementById(GetPublicationAnnouncementInput input) throws Exception  {
        GetPublicationAnnouncementOutput output = new GetPublicationAnnouncementOutput();

        PublicationAnnouncement object=publicationAnnouncementMapper.selectByPrimaryKey(input.getId());

        //Example example = new Example(ColumnPlate.class);
        //Example.Criteria criteria = example.createCriteria();

        //criteria.andEqualTo("keyType",input.getPublishType());//2:公告 3：发文
        //List<ColumnPlate> lsTwo=columnPlateMapper.selectByExample(example);
        //output.setColumnPlates(lsTwo);
        if(input.getType()!=null&&input.getType().equals("view")){
            CreateBrowseRecordInput cbrInput=new CreateBrowseRecordInput(){
            };
            BrowseRecord br=new BrowseRecord();
            br.setArticleId(input.getId());
            br.setUsercode("");
            br.setUserid("");
            br.setUsername("");
            br.setKeyType(object.getPublishType());
            //br.setKeyType(input.g);
            cbrInput.setItem(br);
            browseRecordService.createBrowseRecord(cbrInput);
        }


        GetBrowseCountInput countInput=new GetBrowseCountInput();
        countInput.setId(object.getId());
        countInput.setKeyType(object.getPublishType());
        Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
        object.setBroweCount(count);

        output.setItem(object);
        //scopes
        Example example=new Example(ReleaseScope.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("keyId",object.getId());
        criteria.andEqualTo("deleted","0");
       // Long[] types=new Long[]{2L,3L};
        List<Long> types=new ArrayList<Long>();
        types.add(2L);
        types.add(3L);
        criteria.andIn("publishType",types);
        List<ReleaseScope> releaseScopes=releaseScopeMapper.selectByExample(example);
        output.setReleaseScopes(releaseScopes);

        object.setFiles(fileService.getFiles(object.getId().toString(),FileBusinessType.PublicationAnnouncement.toString()));
        return  output;
    }
/**
 *  创建人:王增立
 *  备注: 获取首页公告、发文信息
 *  时间: 2019/4/26 18:38
 *  参数: 
 */
    public GetPublicationAnnouncementOutput getHomePageNewsCollege(GetHomePagePublicationAnnouncementInput input) throws Exception {
        GetPublicationAnnouncementOutput output = new GetPublicationAnnouncementOutput();
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath(input.getPublishType());

        input.setOrgPathIDs(PrivilegeToolList.getOrgIdPath());
        List<PublicationAnnouncement> ls= new ArrayList();
        if(PrivilegeToolList.isAdmin()){
            ls = publicationAnnouncementMapper.selectAdminBylimit(input);
        }else{
            ls = publicationAnnouncementMapper.selectBylimit(input);
        }


        PageInfo<PublicationAnnouncement> page = new PageInfo<>(ls);
        List<PublicationAnnouncement> resultLs= page.getList();
        for(PublicationAnnouncement item:resultLs){
            item.setFiles(fileService.getFiles(item.getId().toString(), FileBusinessType.PublicationAnnouncement.toString()));
        }
        //浏览次数
        List<PublicationAnnouncement> lsResult=page.getList();
        lsResult.forEach(it->{
            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);
        });

        output.setItems(new PagedResult<PublicationAnnouncement>(lsResult, (int) page.getTotal()));
        return output;

    }
}
